package com.chat.server;

import com.alibaba.fastjson.JSON;
import com.chat.entity.Message;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@ServerEndpoint("/{name}")
public class WsServer {

    /**
     * 记录所有的在线用户
     */
    private static Map<String, WsServer> clients = new HashMap<>();

    /**
     * 当前用户的名称
     */
    private String name;

    /**
     * 本地会话
     */
    private Session session;

    /**
     *  建立新的链接时调用
     */
    @OnOpen
    public void onOpen(@PathParam("name")String name, Session session){

        //  判断名称是否使用了关键字
        if (name.equals("all")){
            session.getAsyncRemote().sendText("不允许使用all作为名称");
            try {
                session.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }

        //  判断该名称是否被使用
        WsServer client = clients.get(name);
        if (client!=null){

            session.getAsyncRemote().sendText(name + "名称已经被使用，请重新取名");
            try {
                session.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }

        this.name = name;
        this.session = session;

        //  记录当前用户
        clients.put(name, this);

        // 欢迎新用户
        String msg = "欢迎用户 '" + name + "' 来到小阳交友平台"+"\t在线人数为：" + clients.size() + "\n" + "请选择你要发送的好友：\n";

        int count = 0;
        for (String tName : clients.keySet()) {
            msg += tName + '\t';
            count++;
            if (count % 8 == 0){
                msg += '\n';
            }
        }
        if (msg.charAt(msg.length()-1)!='\n'){
            msg += '\n';
        }
        msg += "请以 receiver(all发送给所有人) content 的格式发送消息\n";
        Message message = new Message();
        message.setContent(msg);
        message.setSender("通知");
        for (WsServer wsServer : clients.values()) {
            wsServer.session.getAsyncRemote().sendText(JSON.toJSONString(message));
        }
    }

    @OnClose
    public void onClose(){

        // 去除下线用户
        clients.remove(name);

        Message message = new Message();
        message.setSender("通知");
        message.setContent("用户 '" + name + "已下线");

        //  通知所有用户该用户已下线
        for (WsServer wsServer : clients.values()) {
            wsServer.session.getAsyncRemote().sendText(JSON.toJSONString(message));
        }
        System.out.println("用户 '" + name + "已下线");
    }

    @OnError
    public void  onError(Session session, Throwable error){

        System.out.println("发生错误" + error.getMessage());
    }

    @OnMessage
    public void onMessage(String message,Session session){
        Message userMessage = JSON.parseObject(message, Message.class);
        //  判断该消息是发给谁的
        if (userMessage.getReceiver().equals("all")){
            // 发给所有人
            for (WsServer wsServer : clients.values()) {
                if (clients.get(userMessage.getSender())!=wsServer){
                    wsServer.session.getAsyncRemote().sendText(JSON.toJSONString(userMessage));
                }
            }
            return;
        }

        WsServer wsServer = clients.get(userMessage.getReceiver());
        wsServer.session.getAsyncRemote().sendText(JSON.toJSONString(userMessage));
    }
}
